<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>差旅报账</title>
    <jsp:include page="../head.jsp"></jsp:include>
    <style>
        .img-list{
            display: flex;
            flex-flow: row wrap;
            align-content: flex-start;
        }

        .item{
            width: 100px;
            height: 100px;
            border: 1px solid gray;
            margin: 10px;
            position: relative;
        }

        .item img{

            width: auto;
            height: auto;
            max-width: 100%;
            max-height: 100%;
        }

        .handle{
            position: absolute;
            width: 100px;
            height: 20px;
            background: rgba(0,0,0,0.1);
            text-align: center;
            bottom: 0;
        }
        .handle:hover{
            background: rgba(0,0,0,0.2);
        }

        .dialog{
            position: absolute;
            top:0;
            left: 0;
            right: 0;
            bottom: 0;
            display: flex;
            justify-items: center;
            align-items: center;
        }

        .dialog > div{
            width: 300px;
            height: 400px;
            background: white;
        }
    </style>

</head>
<body>

    <div class="layui-container">
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
            <legend><b>差旅报销</b></legend>
        </fieldset>
        <div class="layui-card">
            <div class="layui-card-header">基本信息</div>
            <div class="layui-card-body">
                <form class="layui-form" id="top-form" action="" lay-filter="top-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">出差日期:</label>
                        <div class="layui-inline">
                            <input type="text" id="startDate" name="startDate" placeholder="请输入起始日期" autocomplete="off" class="layui-input">
                        </div>
                        <div class="layui-inline"><span>-</span></div>
                        <div class="layui-inline">
                            <input type="text" id="endDate" name="endDate" placeholder="请输入起始日期" autocomplete="off" class="layui-input">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">出差事由:</label>
                            <div class="layui-input-inline">
                                <input type="text" name="reasons" placeholder="请输入出差事由" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">出差地点:</label>
                            <div class="layui-input-inline">
                                <input type="text" name="address" placeholder="请输入出差地点" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">出差人:</label>
                            <div class="layui-input-inline">
                                <input type="text" name="proposerName" placeholder="请输入申请人" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <div class="layui-card">
            <div class="layui-card-header">交通费</div>
            <div class="layui-card-body">
                <button class="layui-btn layui-btn-normal addBtn" data-idx="1">添加</button>
                <table class="layui-table" lay-data="{page:false,id:'traffic',totalRow: true}" id="traffic" lay-filter="traffic">
                    <thead>
                    <tr>
                        <th lay-data="{field:'typeName', width:120,edit: 'text', totalRowText: '合计'}">项目</th>
                        <th lay-data="{field:'origin', edit: 'text'}">起点站</th>
                        <th lay-data="{field:'destination', edit: 'text'}">终点站</th>
                        <th lay-data="{field:'startTime', event: 'setTime'}">出发时间</th>
                        <th lay-data="{field:'arriveTime',event: 'setTime'}">到达时间</th>
                        <th lay-data="{field:'count', width: 100}">张数</th>
                        <th lay-data="{field:'amount', width:100, edit: 'text',totalRow: true}">金额</th>
                        <th lay-data="{title:'操作', toolbar: '#toolbar', width:100}">操作</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>

        <div class="layui-card">
            <div class="layui-card-header">住宿费</div>
            <div class="layui-card-body">
                <button class="layui-btn layui-btn-normal addBtn" data-idx="2">添加</button>
                <table class="layui-table" lay-data="{page:false,id:'hotel',totalRow: true}" lay-filter="hotel">
                    <thead>
                    <tr>
                        <th lay-data="{field:'hotelName', width:200, edit: 'text'}">酒店名称</th>
                        <th lay-data="{field:'startTime', event: 'setTime'}">入住时间</th>
                        <th lay-data="{field:'endTime', event: 'setTime'}">退房时间</th>
                        <th lay-data="{field:'peopleCount', edit: 'text', width: 100}">人数</th>
                        <th lay-data="{field:'price', width:100, edit: 'text'}">单价</th>
                        <th lay-data="{field:'days', width:100, edit: 'text'}">天数</th>
                        <th lay-data="{field:'amount', width:100, totalRow: true}">总价</th>
                        <th lay-data="{title:'操作', toolbar: '#toolbar', width:100}">操作</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>

        <div class="layui-card">
            <div class="layui-card-header">其他费用</div>
            <div class="layui-card-body">
                <button class="layui-btn layui-btn-normal addBtn" data-idx="3">添加</button>
                <table class="layui-table" lay-data="{page:false,id:'other',totalRow: true}" lay-filter="other">
                    <thead>
                    <tr>
                        <th lay-data="{field:'typeName', width:200, edit: 'text'}">名称</th>
                        <th lay-data="{field:'date', width:200, event: 'setTime'}">日期</th>
                        <th lay-data="{field:'remark', width:200, edit: 'text'}">描述</th>
                        <th lay-data="{field:'amount', width:100, edit: 'text',totalRow: true}">金额</th>
                        <th lay-data="{title:'操作', toolbar: '#toolbar', width:100}">操作</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>

        <div class="layui-card">
            <div class="layui-card-header">总计</div>
            <div class="layui-card-body">总计￥：<span id="total">0</span></div>
        </div>

        <div class="layui-card">
            <div class="layui-card-header">票据照片</div>
            <div class="layui-card-body">
                <div class="layui-upload">
                    <button type="button" class="layui-btn layui-btn-normal" id="imgBtn">选择</button>
                    <div class="img-list"></div>
                </div>
            </div>
        </div>

        <div style="text-align: center">
            <button class="layui-btn next" id="submit" style="width: 100px">提交</button>
        </div>
    </div>

    <script type="text/html" id="toolbar">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="remove">删除</button>
        </div>
    </script>

    <script type="text/html" id="imgItem">
        <div class="item">
            <div class="handle" data-idx="">
                <i class="layui-icon layui-icon-delete" style="font-size: 20px" data-idx=""></i>
            </div>
            <img src="">
        </div>
    </script>

    <script src="static/layui/layui.js"></script>
<script>
    layui.use(['table','upload','laydate'], function() {
        var table = layui.table, upload = layui.upload, laydate = layui.laydate;
        var files = {};
        var tableData;

        //监听单元格事件
        table.on('tool(traffic)', function(obj){
            var data = obj.data;
            if(obj.event === 'setTime'){
                var field = $(this).data('field');
                setDate(data,field,obj,this.firstChild,this)
            } else if(obj.event === 'remove'){
                delRow(obj,'traffic')
                setTotal()
            }
        });
        table.on('tool(hotel)', function(obj){
            var data = obj.data;
            if(obj.event === 'setTime'){
                var field = $(this).data('field');
                setDate(data,field,obj,this.firstChild,this)
            }else if(obj.event === 'remove'){
                delRow(obj,'hotel')
                setTotal()
            }
        });
        table.on('tool(other)', function(obj){
            var data = obj.data;
            if(obj.event === 'setTime'){
                var field = $(this).data('field');
                setDate(data,field,obj,this.firstChild,this)
            }else if(obj.event === 'remove'){
                delRow(obj,'other')
                setTotal()
            }
        });
        //监听单元格编辑
        table.on('edit(traffic)', function(obj){
            console.log(obj)
            var old = table.cache['traffic']
            table.reload('traffic',{data:old})
            setTotal()
        });
        table.on('edit(hotel)', function(obj){
            var field = obj.field;
            if(field === 'price' || field === 'days'){
                var price = obj.data.price
                var days = obj.data.days
                obj.data.amount = price * days
                obj.update(obj.data);
            }
            var old = table.cache['hotel']
            table.reload('hotel',{data:old})
            setTotal()
        });
        table.on('edit(other)', function(obj){
            var old = table.cache['other']
            table.reload('other',{data:old})
            setTotal()
        });

        upload.render({
            elem: '#imgBtn'
            ,url: ''
            ,auto:false
            ,multiple: true
            ,acceptMime:"image/*"
            ,accept:"images"
            ,choose: function(obj) {
                //将每次选择的文件追加到文件队列
                files = obj.pushFile();
                console.log(files)
                //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                obj.preview(function (index, file, result) {
                    var item = $($('#imgItem').html())
                    item.find('div').attr('data-idx',index)
                    item.find('i').attr('data-idx',index)
                    item.find('img').attr('src',result)
                    $('.img-list').append(item)
                });
            }
        });

        laydate.render({
            elem: '#startDate'
        });
        laydate.render({
            elem: '#endDate'
        });

        setImgitemClick()

        $('#submit').click(function () {
            var formData = $('#top-form').serializeArray()
            var trafficData = table.cache['traffic'];
            var hotelData = table.cache['hotel'];
            var otherData = table.cache['other'];

            if (!check(formData,trafficData,hotelData,otherData)) return;
            send(formData,trafficData,hotelData,otherData);
        })

        $('.addBtn').click(function () {
            addBtnClick(this)
        })

        function delRow(obj,tableId) {
            obj.del();
            var cacheArr = table.cache[tableId];
            cacheArr.forEach(function (item,i) {
                if(Object.prototype.toString.call(item) === '[object Array]' && item.length === 0){
                    cacheArr.splice(i,1)
                }
            })
            console.log(cacheArr)
            table.reload(tableId,{data:cacheArr})
        }

        function setTotal() {
            var trafficArr = table.cache['traffic']
            var hotelArr = table.cache['hotel']
            var otherArr = table.cache['other']
            console.log(trafficArr)
            console.log(hotelArr)
            console.log(otherArr)
            var tot = 0;
            trafficArr.forEach(function (obj) {
                tot += parseFloat(obj.amount)
            })
            hotelArr.forEach(function (obj) {
                tot += parseFloat(obj.amount)
            })
            otherArr.forEach(function (obj) {
                tot += parseFloat(obj.amount)
            })
            $('#total').text(tot)
        }
        
        function showMsg(msg) {
            layer.msg(msg,{icon:8,time:1000,offset:'200px'})
        }

        function setDate(data,field,obj,element,closeStopElem) {
            laydate.render({
                elem: element
                , show: true //直接显示
                , closeStop: closeStopElem
                , done: function (value, date) {
                    data[field] = value;
                    obj.update(data);
                }
            });
        }

        function send(formData,trafficData,hotelData,otherData) {
            var data= new FormData()
            var formobj = {};
            $.each(formData, function(index,field) {
                formobj[field.name] = field.value;
            })

            trafficData.forEach(function (item) {
                delete item.LAY_TABLE_INDEX
            })
            hotelData.forEach(function (item) {
                delete item.LAY_TABLE_INDEX
            })
            otherData.forEach(function (item) {
                delete item.LAY_TABLE_INDEX
            })

            console.log(formData)
            console.log(trafficData)
            console.log(hotelData)
            console.log(otherData)

            data.append("bizInfo",JSON.stringify(formobj));
            data.append("traffic",JSON.stringify(trafficData));
            data.append("hotel",JSON.stringify(hotelData));
            data.append("other",JSON.stringify(otherData));
            data.append("total",$('#total').text());

            console.log(data)

            for (var item in files) {
                data.append("file",files[item]);
            }

            $.ajax({
                url: "/bill/business/add",
                type: "POST",
                data: data,
                async: false,
                contentType: false,
                processData: false,
                error: function (res) {
                    console.log(res)
                    layer.msg('网络超时',{icon:5});
                },
                success: function (data) {
                    console.log(res)
                    // layer.msg('成功',{icon:6,time:1000},function () {
                    //     resetPage()
                    // });
                },
                complete:function (res) {
                    console.log(res)
                }
            })
        }

        function check(formData,trafficData,hotelData,otherData) {
            var flag = true;
            for (var i = 0; i < formData.length; i++) {
                if(formData[i].value == ""){
                    showMsg("基本信息不完整")
                    flag = false;
                    break;
                }
            }
            if (!flag) return flag;

            if(trafficData.length == 0 && hotelData.length == 0 && otherData.length == 0){
                showMsg("请添加申报的内容")
                flag = false;
                return flag;
            }else{
                if(trafficData.length > 0){
                    if (!checkItemEmpty(trafficData)){
                        showMsg("交通费用内容不完整")
                        flag = false;
                        return flag;
                    }
                }
                if(hotelData.length > 0){
                    if (!checkItemEmpty(hotelData)){
                        showMsg("住宿费用内容不完整")
                        flag = false;
                        return flag;
                    }
                }
                if(otherData.length > 0){
                    if (!checkItemEmpty(otherData)){
                        showMsg("其他费用内容不完整")
                        flag = false;
                        return flag;
                    }
                }
            }

            return flag;
        }

        function checkItemEmpty(objArr) {
            var flag = true;
            objArr.forEach(function (obj) {
                for(var key in obj){
                    console.log(obj[key],obj[key] === undefined , obj[key] === '')
                    if(obj[key] === undefined || obj[key] === ''){
                        console.log(obj[key])
                        flag = false;
                    }
                }
            })
            return flag;
        }

        function addRow(tableId,row) {
            var old = table.cache[tableId];
            old.push(row)
            console.log(old)
            table.reload(tableId,{data:old})
        }

        function addBtnClick(e) {
            console.log(e)
            var index = $(e).attr('data-idx');
            if(index == 1){
                var row = {typeName:'',amount:'',origin:'',destination:'',startTime:'',arriveTime:'',count:1}
                addRow('traffic',row)
            }else if(index == 2){
                var row = {hotelName:'',startTime:'',endTime:'',peopleCount:'',price:'',days:'',amount:''}
                addRow('hotel',row)
            }else if(index == 3){
                var row = {typeName:'',amount:'',date:'',remark:''}
                addRow('other',row)
            }
        }

        function resetPage() {
            $('.img-list').children().remove()
            table.reload('traffic',{data:{}})
            table.reload('hotel',{data:{}})
            table.reload('other',{data:{}})
            $('#total').text('')
        }

        function setImgitemClick(){
            $('.img-list').click(function (e) {
                var target = $(e.target)
                if(target.hasClass('handle') || target.hasClass('layui-icon')){
                    var dataIdx = target.attr('data-idx')
                    delete files[dataIdx];
                    target.parents('.item').remove()
                }
            })
        }
    })
</script>
</body>
</html>
